import logging
from config.ServerApp import app
from logging.handlers import TimedRotatingFileHandler
from sanic.log import logger
from config.LoadConfig import get_config
import os
from utils.PathUtil import build_save_file_dir


__system_conf = get_config("system")
__simple_server_name = __system_conf['simple_server_name'] # 服务简易名称
# /home/admin/logs
log_root_path=build_save_file_dir("logs")
if not os.path.exists(log_root_path):
        os.makedirs(log_root_path)

def setup_logging():
    log_filename = __simple_server_name+".log"
    log_path = log_root_path
    log_level = logging.INFO
    when = 'midnight'
    interval = 1
    backupCount = 7
    full_log_path = f"{log_path}/{log_filename}"
    if os.path.exists(full_log_path):
        with open(full_log_path, 'w') as f:
            f.write("")
    handler = TimedRotatingFileHandler(
        full_log_path, when=when, interval=interval, backupCount=backupCount, encoding='utf-8'
    )
    handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(log_level)
    return logger



# 设置日志记录器
ph_ocr_logger = setup_logging()
app.ctx.logger = ph_ocr_logger
@app.listener('before_server_start')
async def setup_logging(app, loop):
    # 确保在事件中也使用相同的日志记录器
    app.ctx.logger = ph_ocr_logger
    
